package org.peterf.foxish.texture;

import java.util.HashMap;
import java.util.Map.Entry;

import org.peterf.foxish.util.Pair;

public class TextureRepository {

    private static HashMap<Integer, Pair<Texture, Boolean>> repo = new HashMap<Integer, Pair<Texture, Boolean>>();

    public static void destroy() {
        repo.clear();
    }

    public static Texture get(int resId) {
        return find(resId).shared();
    }

    public static void preLoad(int resId) {
        find(resId);
    }

    public static void recreate() {
        for (Entry<Integer, Pair<Texture, Boolean>> e : repo.entrySet()) {
            e.getValue().second = false;
        }
    }

    private static Texture find(int resId) {
        Pair<Texture, Boolean> pair = repo.get(resId);
        if (pair == null) {
            Texture texture = TextureUtil.getTexture(resId);
            pair = new Pair<Texture, Boolean>(texture, true);
            repo.put(resId, pair);
        } else if (!pair.second) {
            pair.first = TextureUtil.getTexture(resId);
            pair.second = true;
        }
        return pair.first;
    }

}
